<?php

namespace Frieza\Modules\Search\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\SearchKeyword;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;


class SearchAdvController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    private function _filterWhere($params)
    {
        if (isset($params['_columns_'])) {
            unset($params['_columns_']);
        }
        if (isset($params['_pjax'])) {
            unset($params['_pjax']);
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);
        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
            }
        }
        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }

    public function index(Request $request, Content $content, $type)
    {
        $request = $request->all();
        $request = self::_filterWhere($request);

        $tab = new Tab();
        $tab->addLink(SearchKeyword::MATCH_TYPE[SearchKeyword::MATCH_TYPE_RES_HOT_ADV], '/admin/search/adv/' . SearchKeyword::MATCH_TYPE_RES_HOT_ADV, $type == SearchKeyword::MATCH_TYPE_RES_HOT_ADV);
        $tab->addLink(SearchKeyword::MATCH_TYPE[SearchKeyword::MATCH_TYPE_PRE_KEY_ADV], '/admin/search/adv/' . SearchKeyword::MATCH_TYPE_PRE_KEY_ADV, $type == SearchKeyword::MATCH_TYPE_PRE_KEY_ADV);
        $tab->addLink(SearchKeyword::MATCH_TYPE[SearchKeyword::MATCH_TYPE_KEY_CONTENT], '/admin/search/adv/' . SearchKeyword::MATCH_TYPE_KEY_CONTENT, $type == SearchKeyword::MATCH_TYPE_KEY_CONTENT);
        $list = null;
        switch ($type) {
            case SearchKeyword::MATCH_TYPE_RES_HOT_ADV:
                $list = $this->getHotAdvGrid($request);
                break;
            case SearchKeyword::MATCH_TYPE_PRE_KEY_ADV:
                $list = $this->getPreKeyAdvGrid($request);
                break;
            case SearchKeyword::MATCH_TYPE_KEY_CONTENT:
                $list = $this->getKeyContentGrid($request);
                break;
        }
        return $content
            ->header('搜索词广告管理')
            ->breadcrumb(
                ['text' => '搜索词广告管理', 'url' => '/search/adv/' . $type]
            )
            ->body($tab)->row($list);
    }

    private function getHotAdvGrid($request)
    {
        $limitArr = $request['LIMIT'];
        $where = [
            'recommend_keyword[~]' => (string)$request['AND']['recommend_keyword'],
        ];
        if ($request['AND']['input_keyword']) {
            $where['input_keyword[~]'] = array($request['AND']['input_keyword']);
        }
        $where = array_filter($where);
        $lists = SearchKeyword::getKeywordsByMatchType(SearchKeyword::MATCH_TYPE_RES_HOT_ADV, $limitArr, $where);
        $lists_all = SearchKeyword::getKeywordsByMatchType(SearchKeyword::MATCH_TYPE_RES_HOT_ADV, [], $where);

        $gridModel = new pGridDataModel($lists, count($lists_all), [
            'perPage' => $request['per_page'] ?: $request['LIMIT'][1]
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('input_keyword', '搜索词')->placeholder('搜索词(模糊匹配)');
                });

                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('recommend_keyword', '推荐词')->placeholder('推荐词(模糊匹配)');
                });

            });

            $grid->column('id');
            $grid->column('input_keyword', '搜索词')->width(150);
            $grid->column('recommend_keyword', '推荐词')->display(function () {
                $html = '';
                $keyWords = explode(',', $this->recommend_keyword);
                foreach ($keyWords as $value) {
                    $arr = explode('|', $value);
                    $html .= '<p>词：' .  (isset($arr[0]) ? $arr[0] : "")  . '；位置：' . (isset($arr[1]) ? $arr[1] : "") . '</p>';
                }
                return $html;
            });
            $grid->column('start_time', '开始展示时间');
            $grid->column('end_time', '展示结束时间');
            $grid->column('addtime', '添加时间');
            $grid->column('edittime', '修改时间');
            $grid->column('keyword_sort', '排序');
            $grid->column('admin_id', '操作人')->display(function () {
                if (!$this->admin_id) {
                    return '暂无';
                } else {
                    return Admin::user()->find($this->admin_id)->name;
                }
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    private function getPreKeyAdvGrid($request)
    {
        $limitArr = $request['LIMIT'];
        $where = [
            'recommend_keyword[~]' => (string)$request['AND']['recommend_keyword'],
        ];
        if ($request['AND']['input_keyword']) {
            $where['input_keyword[~]'] = array($request['AND']['input_keyword']);
        }
        $where = array_filter($where);
        $lists = SearchKeyword::getKeywordsByMatchType(SearchKeyword::MATCH_TYPE_PRE_KEY_ADV, $limitArr, $where);
        $lists_all = SearchKeyword::getKeywordsByMatchType(SearchKeyword::MATCH_TYPE_PRE_KEY_ADV, [], $where);

        $gridModel = new pGridDataModel($lists, count($lists_all), [
            'perPage' => $request['per_page'] ?: $request['LIMIT'][1]
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('input_keyword', '搜索词')->placeholder('搜索词(模糊匹配)');
                });

                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('recommend_keyword', '推荐词')->placeholder('推荐词(模糊匹配)');
                });

            });

            $grid->column('id');
            $grid->column('input_keyword', '搜索词')->width(150);
            $grid->column('recommend_keyword', '推荐词')->width(150);
            $grid->column('start_time', '开始展示时间');
            $grid->column('end_time', '展示结束时间');
            $grid->column('addtime', '添加时间');
            $grid->column('edittime', '修改时间');
            $grid->column('keyword_sort', '排序');
            $grid->column('admin_id', '操作人')->display(function () {
                if (!$this->admin_id) {
                    return '暂无';
                } else {
                    return Admin::user()->find($this->admin_id)->name;
                }
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    private function getKeyContentGrid($request)
    {
        $limitArr = $request['LIMIT'];
        $where = [
            'recommend_keyword[~]' => (string)$request['AND']['recommend_keyword'],
        ];
        if ($request['AND']['input_keyword']) {
            $where['input_keyword[~]'] = array($request['AND']['input_keyword']);
        }
        $where = array_filter($where);
        $lists = SearchKeyword::getKeywordsByMatchType(SearchKeyword::MATCH_TYPE_KEY_CONTENT, $limitArr, $where);
        $lists_all = SearchKeyword::getKeywordsByMatchType(SearchKeyword::MATCH_TYPE_KEY_CONTENT, [], $where);

        $gridModel = new pGridDataModel($lists, count($lists_all), [
            'perPage' => $request['per_page'] ?: $request['LIMIT'][1]
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('input_keyword', '搜索词')->placeholder('搜索词(模糊匹配)');
                });

                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('recommend_keyword', '内容id')->placeholder('内容id(模糊匹配)');
                });

            });

            $grid->column('id');
            $grid->column('input_keyword', '搜索词')->width(150);
            $grid->column('recommend_keyword', '内容id')->display(function () {
                return explode(',', $this->recommend_keyword);
            })->label('success')->setAttributes(['style' => 'word-break:break-all; word-wrap:break-all;width:100px']);
            $grid->column('start_time', '开始展示时间');
            $grid->column('end_time', '展示结束时间');
            $grid->column('addtime', '添加时间');
            $grid->column('edittime', '修改时间');
            $grid->column('keyword_sort', '排序');
            $grid->column('admin_id', '操作人')->display(function () {
                if (!$this->admin_id) {
                    return '暂无';
                } else {
                    return Admin::user()->find($this->admin_id)->name;
                }
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    //
    public function edit(Request $request, Content $content, $type, $id = 0)
    {
        $header = '搜索词广告管理';
        switch ($type) {
            case SearchKeyword::MATCH_TYPE_RES_HOT_ADV:
                $header = '搜索结果热词广告管理';
                break;
            case SearchKeyword::MATCH_TYPE_PRE_KEY_ADV:
                $header = '搜索预置词广告管理';
                break;
            case SearchKeyword::MATCH_TYPE_KEY_CONTENT:
                $header = '搜索词配置内容管理';
                break;
        }
        $request = $request->all();
        if ($id == 0) {
            return $content
                ->header($header)
                ->breadcrumb(
                    ['text' => '搜索词广告管理', 'url' => '/search/adv/' . $type],
                    ['text' => $header, 'url' => '/search/adv/' . $type . '/create']
                )
                ->body(self::editAction($request, $type, $id, True));
        } else {
            return $content
                ->header($header)
                ->breadcrumb(
                    ['text' => '搜索词广告管理', 'url' => '/search/adv/' . $type],
                    ['text' => $header, 'url' => '/search/adv/' . $type . '/' . $id . '/edit']
                )
                ->body(self::editAction($request, $type, $id, False));
        }
    }

    public function editAction($request, $type, $id = 0, $isCreate = false)
    {
        if ($isCreate) {
            $info['match_type'] = $type;
            $form = new Form($info);
            $form->hidden('match_type');
            $form->text('input_keyword', '搜索词')->required('不能为空');
            if ($type == SearchKeyword::MATCH_TYPE_RES_HOT_ADV) {
                $form->textarea('recommend_keyword', '推荐词')->rows(10)->required('不能为空')->help('一行一个，推荐词|插入位置，例: 洗衣机|5');
            } else if ($type == SearchKeyword::MATCH_TYPE_PRE_KEY_ADV) {
                $form->text('recommend_keyword', '推荐词')->required('不能为空');
            } else if ($type == SearchKeyword::MATCH_TYPE_KEY_CONTENT) {
                $form->textarea('recommend_keyword', '推荐内容id')->required('不能为空')->help('内容id，以英文逗号分隔');
            }
        } else {
            $info = SearchKeyword::getKeywordById($id);
            switch ($type) {
                case SearchKeyword::MATCH_TYPE_RES_HOT_ADV:
                    $info['recommend_keyword'] = str_replace(",", "\r\n", $info['recommend_keyword']);
                    break;
            }
            $form = new Form($info);
            $form->hidden('id');
            $form->hidden('match_type');
            $form->text('input_keyword', '搜索词')->required('不能为空')->required()->readonly();
            if ($type == SearchKeyword::MATCH_TYPE_RES_HOT_ADV) {
                $form->textarea('recommend_keyword', '推荐词')->rows(10)->required('不能为空')->help('一行一个，推荐词|插入位置，例: 洗衣机|5');
            } else if ($type == SearchKeyword::MATCH_TYPE_PRE_KEY_ADV) {
                $form->text('recommend_keyword', '推荐词')->required('不能为空');
            } else if ($type == SearchKeyword::MATCH_TYPE_KEY_CONTENT) {
                $form->textarea('recommend_keyword', '推荐内容id')->required('不能为空')->help('内容id，以英文逗号分隔');
            }
        }
        $form->datetime('start_time', '开始展示时间')->required('不能为空');
        $form->datetime('end_time', '展示结束时间')->required('不能为空');
        $form->number('keyword_sort', '排序')->help('相同搜索词展示排序大的推荐词')->required('不能为空')->default(0);

        $form->action('/admin/search/adv/save');

        return $form->render();
    }

    public function del($step, $id)
    {
        $rs = SearchKeyword::del($id);
        if ($rs) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }
    }

    public function save(Request $request)
    {
        $request = $request->all();
        $id = (int)$request['id'];
        $matchType = $request['match_type'];
        $recommendKeyword = $request['recommend_keyword'];
        switch ($matchType) {
            case SearchKeyword::MATCH_TYPE_RES_HOT_ADV:
                $recommendKeyword = str_replace("\r\n", ",", $recommendKeyword);
                break;
            case SearchKeyword::MATCH_TYPE_KEY_CONTENT:
                $recommendKeyword = str_replace(["，", "\r\n"], ",", $recommendKeyword);
                break;
        }

        $data = [
            'input_keyword' => $request['input_keyword'],
            'match_type' => $matchType,
            'recommend_keyword' => $recommendKeyword,
            'show_type' => SearchKeyword::SHOW_TYPE_TEMP,
            'content_type' => SearchKeyword::CONTENT_TYPE_ADV,
            'start_time' => $request['start_time'],
            'end_time' => $request['end_time'],
            'keyword_sort' => $request['keyword_sort'],
            'admin_id' => Admin::user()->id,
        ];

        //校验数据
        if ((!$data['end_time'] || strtotime($data['end_time']) <= strtotime($data['start_time']))) {
            $error = new MessageBag([
                'title' => '展示时间为一定要配结束时间哦'
            ]);
            return back()->withInput(compact('error'));
        }

        if ($id) {
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $rs = SearchKeyword::updateData($id, $data);
        } else {
            $data['match_type'] = $request['match_type'];
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $rs = SearchKeyword::addData($data);
        }

        if ($rs) {
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/search/adv/' . $matchType)->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            return redirect('/admin/search/index/' . $matchType)->with(compact('error'));
        }


    }


}